<template>
    <div class="controls flex gap-1 mb-4">
        <Button v-if="isTyping" variant="outline" class="bg-red-500 text-white" @click="stopTyping">Stop Typing</Button>
        <Button v-if="!isTyping" variant="outline" class="bg-indigo-500 text-white"  @click="resumeTyping">Resume Typing</Button>
    </div>
   <div class="typewriter-container">
        <h1 class="typed-text" ref="textContainer">
            <span v-html="displayedTextWithCursor"></span>
        </h1>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { Button } from '@/components/ui/button'
const textContainer = ref<HTMLElement | null>(null);

const props = defineProps<{
    text: string;
    speed: number;
    autoStart: boolean;
    hideCursorOnComplete: boolean
}>();

const displayedText = ref('');
const currentIndex = ref(0);
const isTyping = ref(false);
let timer: number | null | undefined = null;

const displayedTextWithCursor = computed(() => {
    return isTyping.value 
        ? `${displayedText.value}<span class="cursor"></span>`
        : displayedText.value;
});

const startTyping = () => {
    isTyping.value = true;

    if (timer) clearInterval(timer);

    timer = setInterval(() => {
        if (currentIndex.value < props.text.length) {
            displayedText.value += props.text[currentIndex.value];
            currentIndex.value++;
        } else {
            isTyping.value = !props.hideCursorOnComplete;
            if (typeof timer === 'number') clearInterval(timer);
            timer = null;
        }
    }, props.speed);
};

const stopTyping = () => {
    isTyping.value = false;
    if (timer) {
        clearInterval(timer);
    }
}

const resumeTyping = () => {
    if (!isTyping.value) {
        startTyping();
    }
}

onMounted(() => {
    if (props.autoStart) {
        startTyping();
    }
});

onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
    }
});

watch(() => props.text,
    () => {
        if (props.autoStart) {
            startTyping();
        }
    }, {
    immediate: true
}
);

</script>

<style scoped>
.controls {
    position: relative;
    z-index: 10;
}

.typewriter-container {
    width: 100%;
    /* max-width: 800px; 限制宽度以触发换行 */
    /* margin: 0 auto; */
    padding: 20px;
}

.typed-text {
    font-size: 3rem;
    line-height: 1.3;
    word-wrap: break-word; /* 确保长单词换行 */
    white-space: normal; /* 允许文本自然换行 */
}

.cursor {
    display: inline-block;
    width: 0.4em;
    height: 1em;
    background-color: #000;
    animation: blink 1s step-end infinite;
    vertical-align: text-bottom; /* 与文本底部对齐 */
    margin-left: 1px;
    position: relative;
    top: 2px; /* 微调位置使其与文本完美对齐 */
}

@keyframes blink {

    from,
    to {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }
}

@media (max-width: 768px) {
    .typed-text {
        font-size: 2rem;
    }
}
</style>